#!/usr/bin/env python

from distutils.sysconfig import get_python_lib
import os.path
import os
import sys
from stat import *

def postinstall(prefix='/usr/local/bin', dryrun = False):
    # compute where the source files are
    libbase = get_python_lib()
    libname = 'bototools'
    adir = os.path.join(libbase, libname)

    cmds = ['ec2img', 'ec2ip', 'ec2ls', 'ec2start', 'ec2stop',
            's3cp', 's3ls', 's3rm']

    for i in cmds:
        # python module that was installed
        source =  os.path.join(adir, i + '.py')
        # the executable in /usr/loca/bin that will link to above
        exe = os.path.join(prefix, i)

        sys.stderr.write("Linking %s to %s: " % (exe, source))
        # link 'em
        if dryrun:
            sys.stderr.write(' skipping, dryrun\n')
        else:
            os.unlink(exe)
            os.symlink(source, exe)
            os.chmod(source, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH |S_IXOTH)
            sys.stderr.write(' OK\n')

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-d', '--dryrun', dest="dryrun", action="store_true",
                      default=False, help='Dryrun, don\'t actually install')
    parser.add_option('-p', '--prefix', dest='prefix', default=None,
                      help="location of binary path, e.g. /usr/local/bin, /usr/bin")

    options,args = parser.parse_args()
    if options.prefix is None:
        sys.stderr.write("Must specific -p _path_, such as /usr/local/bin\n")
        sys.exit(1)

    print options.dryrun

    try:
        postinstall(options.prefix, options.dryrun)
    except OSError,e:
        sys.stderr.write("\n\nGot exceptions: %s\n" % str(e))
        sys.stderr.write(" Maybe you mistyped or need to run under 'sudo'\n")
        sys.exit(1)

    sys.exit(0)


